<template>
	<div class="contractForm" v-loading="loading">
		<el-form ref="contractForm" :model="form" :rules="rules" label-width="120px" :show-message="false">
			<el-form-item label="合同类型" prop="contractType">
				<el-radio-group v-model="form.contractType" @change="changeContractType">
					<el-radio v-for="dict in dict.type.contract_type" :key="dict.value" :label="dict.value">{{ dict.label }}
					</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-row>
				<el-col :span="9">
					<el-form-item label="合同主体" prop="partyB">
						<el-select v-model="form.partyB" placeholder="请选择合同主体">
							<el-option v-for="item in partyBOptions" :key="item.id" :label="item.companyName" :value="item.id">
							</el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="9" v-if="form.contractType == 2">
					<el-form-item label="是否新签" prop="contractIsNew">
						<el-radio-group v-model="form.isDue">
							<el-radio v-for="item in contractNewList" :key="item.label" :label="item.value">{{ item.label }}
							</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>
				<el-col :span="4" style="line-height: 36px;" v-show="groupDateFlag">
					<el-checkbox v-model="form.oldAccounts">老账新接</el-checkbox>
				</el-col>
			</el-row>

			<el-card class="box-card" style="margin-bottom: 30px">
				<el-form-item v-for="item of treeData" :key="item.id" :label="item.label">
					<!-- 渲染数据tree -->
					<el-tree :data="item.children" :props="defaultProps" show-checkbox highlight-current node-key="id"
						:ref="'treeDatas' + item.id" class="newTree" v-model="form.checkedNodes"
						@check="(data, checkinfo) => currentChecked(data, checkinfo)" :default-checked-keys="treeDefaultCheck"
						:default-expanded-keys="treeDefaultExpanded" :expand-on-click-node="false">
						<span class="custom-tree-node" slot-scope="{ node, data }">
							<el-row>
								<el-col :span="10">
									<el-input v-if="node.label.includes('其他') && node.label !== '其他服务'" type="text"
										style="display: inline-block; width: 120px;" size="mini" class="width18" placeholder="请输入服务项目"
										v-model="data.otherNote"></el-input>
									<span v-else style="display: inline-block; width: 80px; margin-top: 4px">{{ node.label }}</span>
									<el-radio-group v-model="data.isYearPay" v-if="data.id == 25">
										<el-radio style="margin-right:10px" v-for="item in isYearPayList" :key="item.label"
											:label="item.value">{{ item.label }}
										</el-radio>
									</el-radio-group>
								</el-col>
								<el-col :span="14"
									v-if="!data.children || data.id == 2 || data.id == 26 || data.id == 40 || data.id == 55 || data.id == 67">
									<span>
										<div style="display: flex">
											<el-form-item :prop="'amount' + data.id">
												<el-input size="mini" placeholder="请输入金额" type="number" oninput="if(value<0)value=0"
													v-model.lazy="data.amount" class="width18 def-input-number" @keydown.native.up.prevent
													@keydown.native.down.prevent @mousewheel.native.prevent>
													<template slot="prepend">金额</template>
												</el-input>
											</el-form-item>

											<el-form-item :prop="'noteOrMemo' + data.id">
												<el-input size="mini" placeholder="请输入备注" v-model="data.noteOrMemo" class="notesClass">
													<template slot="prepend">备注</template>
												</el-input>
											</el-form-item>
										</div>
									</span>
								</el-col>
							</el-row>
						</span>
					</el-tree>
				</el-form-item>
			</el-card>
			<el-row>
				<el-col :span="8">
					<el-form-item label="甲方名称（签章）" prop="partyName">
						<span>
							<el-input size="mini" placeholder="请输入甲方名称（签章）" v-model="form.partyName"
								style="width: 100%; margin-top: 5px">
							</el-input>
						</span>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="甲方联系人" prop="partyCallName">
						<span>
							<el-input size="mini" placeholder="请输入甲方联系人" v-model="form.partyCallName"
								style="width: 100%; margin-top: 5px">
							</el-input>
						</span>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="联系方式" prop="partyCallPhone">
						<span>
							<el-input size="mini" placeholder="请输入联系方式" v-model="form.partyCallPhone"
								style="width: 100%; margin-top: 5px">
							</el-input>
						</span>
					</el-form-item>
				</el-col>
			</el-row>

			<el-row type="flex" style="flex-wrap: wrap;">
				<el-col :span="8">
					<el-form-item label="签约日期" prop="signDate">
						<span>
							<el-date-picker style="width: 100%;" v-model="form.signDate" type="date" size="mini" placeholder="选择日期"
								format="yyyy-MM-dd" value-format="yyyy-MM-dd" :picker-options="pickerOptions2">
							</el-date-picker>
						</span>
					</el-form-item>
				</el-col>
				<el-col :span="8" v-show="entrustCycleDayFlag">
					<el-form-item label="办理期限">
						<span>
							<el-input size="mini" style="width: 100%;" clearable type="number" class="def-input-number"
								v-model.number="form.entrustCycleDay" placeholder="请输入办理期限天数"></el-input>
						</span>
					</el-form-item>
				</el-col>
				<el-col :span="10" v-show="groupDateFlag">
					<el-form-item label="服务周期">
						<span>
							<el-date-picker style="width: 250px;" v-model="form.groupDate" type="daterange" align="right"
								unlink-panels range-separator="至" start-placeholder="开始服务日期" end-placeholder="结束服务日期"
								:picker-options="pickerOptions">
							</el-date-picker>
						</span>
					</el-form-item>
				</el-col>
				<!--  :style="{ float: groupDateFlag ? 'none' : 'left' }" -->
				<el-col :span="8" v-show="form.isDue == 1">
					<el-form-item label="首次签约日期" prop="firstSignDate">
						<span>
							<el-date-picker style="width: 100%;" v-model="form.firstSignDate" type="date" size="mini"
								placeholder="选择日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" :picker-options="pickerOptions3">
							</el-date-picker>
						</span>
					</el-form-item>
				</el-col>
				<el-col :span="8" v-show="form.isDue == 1">
					<el-form-item label="续费日期" prop="renewalDate">
						<span>
							<el-date-picker style="width: 100%;" v-model="form.renewalDate" type="date" size="mini" placeholder="选择日期"
								format="yyyy-MM-dd" value-format="yyyy-MM-dd" :picker-options="pickerOptions3">
							</el-date-picker>
						</span>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="18">
					<el-form-item label="付款方式" prop="payMode">
						<span>
							<el-input clearable placeholder="请输入付款方式" size="mini" v-model="form.payMode"
								style="width: 105%; margin-top: 5px">
								<template slot="prepend">具体说明</template>
							</el-input>
						</span>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="18">
					<el-form-item label="备注">
						<span>
							<el-input clearable placeholder="请输入备注" size="mini" v-model="form.contractRemark"
								style="width: 105%; margin-top: 5px">
								<template slot="prepend">具体说明</template>
							</el-input>
						</span>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<div style="float: right">合计：{{ allmount }}</div>
		<div slot="footer" class="dialog-footer">
			<el-button type="primary" @click="submitForm('contractForm', false)">确 定</el-button>
			<el-button type="primary" @click="submitForm('contractForm', true)">预 览</el-button>
			<el-button @click="closeDialog">取 消</el-button>
		</div>
		<!-- 预览合同 -->
		<el-dialog :visible.sync="pdfDialog.show" title="预览合同" append-to-body @close="previewClosed">
			<div class="dialog-wrap">
				<div class="item-title">{{ pdfDialog.title }}</div>
				<div class="item-content-wrap">
					<el-scrollbar>
						<div class="item-content">
							<div class="pdf" id="previewPDF"></div>
						</div>
					</el-scrollbar>
				</div>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import {
	addDetail,
	getPartyBOptions,
	preViewDetail,
} from "@/api/system/detail";
import { openPDF, delTempPDF, contractItem } from "@/api/contract/info";
import { pcaTextArr } from "element-china-area-data";
import Pdfh5 from "pdfh5";
import "pdfh5/css/pdfh5.css";
export default {
	name: "contractDia",
	props: {
		rowObj: {
			type: Object,
		},
	},
	dicts: ["contract_type"],
	data() {
		var checkLegalPersonPhone = (rule, value, callback) => {
			value = this.form.partyCallPhone;
			const phoneReg = /^1[3-9]\d{9}$/; // 匹配中国手机号格式
			if (phoneReg.test(value)) {
				// 校验成功，调用 callback 不传入任何参数
				callback();
			} else {
				// 校验失败，调用 callback 并传入一个 Error 对象
				callback(new Error("手机号格式不正确"));
			}
		};
		return {
			// 可输入金额的节点id 大分类
			parentIds: [2, 26, 40, 55, 67],
			// 默认选中节点
			treeDefaultCheck: [],
			// 默认展开节点
			treeDefaultExpanded: [],
			// 合同类型数据源,
			treeData: [],
			// 是否新签合同
			contractNewList: [{ label: '新签', value: 0 }, { label: '续费', value: 1 }],
			//
			isYearPayList: [{ label: '年付', value: 1 }, { label: '一次性', value: 2 }],
			// 预览合同
			pdfDialog: {
				show: false,
				title: "",
			},
			pdfh5: null,
			blobURL: null,
			fileName: null, // 临时生成的pdf文件名
			groupDateFlag: true,
			entrustCycleDayFlag: true,
			// 选择时间范围的默认范围选项
			pickerOptions: {
				shortcuts: [
					{
						text: "6个月",
						onClick(picker) {
							const end = new Date();
							const start = new Date();
							end.setTime(end.getTime() + 3600 * 1000 * 24 * 183);
							picker.$emit("pick", [start, end]);
						},
					},
					{
						text: "一年",
						onClick(picker) {
							const end = new Date();
							const start = new Date();
							end.setTime(end.getTime() + 3600 * 1000 * 24 * 364);
							picker.$emit("pick", [start, end]);
						},
					},
					{
						text: "14个月",
						onClick(picker) {
							const end = new Date();
							const start = new Date();
							end.setTime(end.getTime() + 3600 * 1000 * 24 * 425);
							picker.$emit("pick", [start, end]);
						},
					},
					{
						text: "两年",
						onClick(picker) {
							const end = new Date();
							const start = new Date();
							end.setTime(end.getTime() + 3600 * 1000 * 24 * 729);
							picker.$emit("pick", [start, end]);
						},
					},
				],
			},
			pickerOptions2: {
				disabledDate(time) {
					return time.getTime() > Date.now();
				},
				shortcuts: [{
					text: '今天',
					onClick(picker) {
						picker.$emit('pick', new Date());
					}
				}, {
					text: '昨天',
					onClick(picker) {
						const date = new Date();
						date.setTime(date.getTime() - 3600 * 1000 * 24);
						picker.$emit('pick', date);
					}
				}]
			},
			pickerOptions3: {
				disabledDate(time) {
					return time.getTime() > Date.now();
				}
			},
			//
			pcaTextArr,
			// 合同主体  公司名
			partyBOptions: [],
			loading: false,
			// 表单
			form: {
				// 老账新接
				oldAccounts: false,
				// 首次签约日期
				firstSignDate: null,
				// 续费日期
				renewalDate: null,
				// 是否新签合同
				isDue: null,
				//已选择的节点
				checkedNodes: [],
				entrustCycleDay: null,
				groupDate: [],
				contractAmount: 0,
				contractType: null,
				contractRemark: null,
				renewStatus: 0,
				partyB: "",
				payMode: '',
				// 甲方名称 联系人 联系方式
				partyName: "",
				partyCallName: "",
				partyCallPhone: "",
				// 签约日期
				signDate: null,
			},

			defaultProps: {
				children: "children",
				label: "label",
			},

			rules: {
				// 合同类别
				contractType: {
					required: true,
					message: "请选择合同类别",
					trigger: "blur",
				},
				// 是否新签合同
				contractIsNew: {
					required: true,
					message: "请确认是否新签合同",
					trigger: "change",
					validator: (rule, value, callback) => {
						value = this.form.isDue;
						if (value !== null) {
							callback();
						} else {
							callback(new Error("请确认是否新签合同"));
						}
					}
				},
				// 合同主体
				partyB: {
					required: true,
					message: "请选择合同主体",
					trigger: "change",
					validator: (rule, value, callback) => {
						value = this.form.partyB;
						if (value !== null && value !== "") {
							callback();
						} else {
							callback(new Error("请选择合同主体"));
						}
					}
				},
				// 付款方式
				payMode: {
					required: true,
					message: "请填写付款方式具体说明",
					trigger: "blur",
				},
				// 甲方名称 联系人 联系方式
				partyName: [{
					required: true,
					message: "请填写甲方名称",
					trigger: "blur",
				}],
				// 甲方联系人
				partyCallName: {
					required: true,
					message: "请填写甲方联系人",
					trigger: "blur",
				},
				// 联系方式
				partyCallPhone: {
					required: true,
					message: "请填写联系方式",
					trigger: "blur",
					validator: checkLegalPersonPhone,
				},
				// 签约日期
				signDate: {
					required: true,
					message: "请选择签约日期",
					trigger: "change",
				},
				// 首次签约日期
				// firstSignDate: {
				// 	required: true,
				// 	message: "请选择首次签约日期",
				// 	trigger: "change",
				// },
				// // 续费日期
				// renewalDate: {
				// 	required: true,
				// 	message: "请选择续费日期",
				// 	trigger: "change",
				// }
			},

		};
	},
	created() {
		let tree = JSON.parse(localStorage.getItem("contractTypeList"));
		// 遍历tree，为tree下的所有子孙节点添加属性 topLevelId,topLevelId为 服务项目几大类的id
		let setTopLevelId = function (child, id) {
			child.forEach(element => {
				if (element.children) {
					element.topLevelId = id;
					setTopLevelId(element.children, id)
				} else {
					element.topLevelId = id;
				}
			});
		}
		tree[0].children.forEach(item => {
			setTopLevelId(item.children, item.id)
		})
		this.treeData = tree;
		// this.getPartyBOptions();
		// 动态向rules添加验证规则
		this.findAmount();
	},

	mounted() {
		// 获取合同主体
		this.getPartyBOptions();
	},

	computed: {
		// 计算总金额  如果父级节点有金额，则不计算子节点金额
		allmount: function () {
			var ans = 0;
			ans = Number(this.form.registerAllAmount || 0)
			let checkAmount = this.form.checkedNodes;
			checkAmount.forEach(item => {
				item.computedFlag = false;
			})
			// 只要子节点有选中并且输入了金额，只计算子节点，不计算特定id的父节点
			// ans += Number(element.amount);
			this.treeData[0].children.forEach(child => {
				if (child.amount !== '') {// 大类节点金额非空,检查子孙节点是否已选中并有金额，如果有则计算子孙类，如果没有则计算大类节点
					// 当子孙节点全部未选中时，计算大类节点
					// 当子孙节点至少有一个选中并且有输入金额时，只计算子孙节点，不计算大类节点
					let parentFlag = true; //是否计算大类节点标记
					let checkedNum = 0;
					let diguiFunc = function (childs) {
						childs.forEach(element => {
							if (element.children) {
								diguiFunc(element.children);
							} else {
								if (element.checked && element.amount !== '') { // 子孙节点有选中，且有输入金额，只计算子孙节点
									ans += Number(element.amount);
									parentFlag = false;
								}
								if (element.checked) {
									checkedNum += 1;
								}
							}
						});
					}
					diguiFunc(child.children)
					if (parentFlag && checkedNum > 0) { //子孙类节点没有选中，计算大类节点
						ans += Number(child.amount);
					}
				} else { // 大类节点金额为空，只考虑计算子孙节点金额
					let diguiFunc = function (childs) {
						childs.forEach(element => {
							if (element.children) {
								diguiFunc(element.children);
							} else {
								if (element.checked && element.amount !== '') { // 子孙节点有选中，且有输入金额，只计算子孙节点
									ans += Number(element.amount);
								}
							}
						});
					}
					diguiFunc(child.children)
				}
			})

			// this.treeData[0].children.forEach(child => {
			// 	if (this.parentIds.includes(child.id)) {
			// 		if (child.amount !== '') {// 大类节点金额非空,计算大类节点，不计算子类节点
			// 			ans += Number(child.amount);
			// 		} else {// 大类节点金额为空，计算子类节点
			// 			checkAmount.forEach(item => {
			// 				if (item.parentId == child.id && !item.computedFlag) {
			// 					ans += Number(item.amount);
			// 					item.computedFlag = true;
			// 				}
			// 			})
			// 		}
			// 	} else {
			// 		checkAmount.forEach(item => {
			// 			console.log('1');
			// 			if (!this.parentIds.includes(item.parentId) && !item.computedFlag) {
			// 				ans += Number(item.amount);
			// 				item.computedFlag = true;
			// 			}
			// 		})
			// 	}
			// })
			this.form.contractAmount = ans;
			return ans;
		},
	},

	methods: {
		// 递归计算，金额

		// treeData添加校验规则
		findAmount() {
			let that = this;
			function traverses(children) {
				children.forEach(child => {
					if (child.children) {
						traverses(child.children);
					} else {
						that.$set(that.rules, `amount${child.id}`,
							[{
								required: true,
								message: '请输入金额',
								trigger: 'blur',
								validator: (rule, value, callback) => {
									let list = that.form.checkedNodes;
									let hasError = false; // 用于跟踪是否有错误发生
									if (list && list.length > 0) {
										for (let index = 0; index < list.length; index++) {
											const element = list[index];
											if (element.id == child.id) {
												// 调用方法，查询child的顶级父类是否有金额输入值
												let flag = findTopLevelId(child.topLevelId);
												// 查找当前元素的兄弟元素是否有金额输入值
												let findSiblingsFlag = findSiblings(child.topLevelId, child.id);
												// 如果当前节点金额为空、备注为空，并且兄弟元素金额为空，则提示错误
												if (child.amount == '' && (child.noteOrMemo == '' || child.noteOrMemo == null)) {
													if (!findSiblingsFlag) {//兄弟节点为空，检查父类节点是否为空
														if (!flag) {//顶级父类金额为空，
															hasError = true; // 如果有错误，设置标志
															break; // 如果只需要找到一个错误就停止检查
														}
													} else {//当前节点为空，兄弟节点不为空，直接报异常，不用判断父类
														hasError = true; // 如果有错误，设置标志
														break; // 如果只需要找到一个错误就停止检查
													}
												}
											}
										}
									}
									// 循环结束后调用回调函数
									if (hasError) {
										// 如果有错误发生，则调用回调函数并传递一个具有描述信息的Error对象
										callback(new Error(""));
									} else {
										// 如果没有错误发生，则正常调用回调函数
										callback();
									}
								}
							}]
						)
					}
				});
			}
			for (let i = 0; i < this.treeData.length; i++) {
				traverses(this.treeData[i].children);
			}
			// 查找顶级父类是否有金额输入
			let findTopLevelId = function (id) {
				let amountFlag = false;
				that.treeData[0].children.forEach(element => {
					if (element.id == id && (element.amount !== '' || element.noteOrMemo !== '')) {
						amountFlag = true;
					}
				});
				return amountFlag;
			}
			// 查找选中节点的 兄弟元素 是否有金额输入
			let findSiblings = function (topLevelId, id) {
				let flag = true;
				let siblingsArray = [];
				let list = that.form.checkedNodes;
				list.forEach(element => {
					if (element.topLevelId == topLevelId && element.id != id) {
						siblingsArray.push(element)
					}
				});
				siblingsArray.forEach(element => {
					if (element.amount == '' && (element.noteOrMemo == '' || element.noteOrMemo == null)) {
						flag = false;
					}
				});
				if (siblingsArray.length == 0) {//没有兄弟节点，直接设置flag为false，表示兄弟节点为空
					flag = false;
				}
				return flag;
			}
		},
		// 合同类别点击，
		changeContractType(e) {
			if (e == 2) {
				// 托管类服务  需要选择服务周期
				this.groupDateFlag = true;
				this.form.entrustCycleDay = null;
				this.entrustCycleDayFlag = false;
			} else {
				this.form.isDue = 0;//非托管业务 isDue为新签
				this.form.groupDate = [];
				this.groupDateFlag = false;
				this.entrustCycleDayFlag = true;
			}
		},
		// 节点点击
		currentChecked(nodeObj, SelectedObj) {
			let checked = null;
			this.form.checkedNodes = SelectedObj.checkedNodes;
			// 如果 checkedKeys 内包含当前节点id则为选中 true，如果不包含则为false
			if (SelectedObj.checkedKeys.includes(nodeObj.id)) {
				checked = true;
				nodeObj.checked = true;
			} else {
				nodeObj.checked = false;
				checked = false
			}
			this.eitherOr(nodeObj, checked);
			// 如果当前节点有children属性时，children子节点的checked应和当前节点的checked同步
			let syncChecked = function (child, checked) {
				child.forEach(element => {
					if (element.children) {
						syncChecked(element.children, checked);
					} else {
						element.checked = checked;
					}
				});
			}
			if (nodeObj.children) {
				syncChecked(nodeObj.children, nodeObj.checked)
			}
		},
		// 特定id下的服务项目仅支持单选   有账/零申报  只可选其一
		eitherOr(nodeObj, checked) {
			let ids = [84, 85, 15, 16, 20, 21];
			// 选中/取消选中节点，需要设置互斥的disabled属性为true/false
			if (ids.includes(nodeObj.id)) {
				function findsiblins(child) {
					child.forEach(item => {
						if (item.children) {
							findsiblins(item.children, checked)
						} else {
							// 如果当前点击节点的id在特定id内，并且该id非点击的节点id，并且节点的父id与点击节点的父id相同，则将当前节点设置为不可选或可选状态
							if (ids.includes(item.id) && item.id !== nodeObj.id && item.parentId == nodeObj.parentId) {
								item.disabled = checked;
							}
						}
					})
				}
				findsiblins(this.treeData[0].children, checked)
			}
		},

		// 预览合同弹层关闭时的处理
		previewClosed() {
			// 当不再需要 fileUrl 时，将其删除
			window.URL.revokeObjectURL(this.blobURL);
			this.blobURL = null;
			//调用接口删除临时pdf文件
			delTempPDF(this.fileName);
			this.fileName = null;
		},

		/** 提交按钮 */
		submitForm(formName, previewFlag) {
			// if (this.form.contractType === null || this.form.contractType === "") {
			// 	this.$modal.msgError("请至少选择一个合同类别");
			// 	return;
			// }

			this.$refs[formName].validate((valid) => {
				if (valid) {
					if (this.form.checkedNodes.length == 0) {
						this.$modal.msgError("请至少选择一个业务");
						return;
					}
					// 托管服务 必须有服务周期
					if (this.form.contractType == '2' && this.form.groupDate.length == 0) {
						this.$modal.msgError("托管服务需要选择服务周期！");
						return;
					}
					// 非托管合同需要填写办理期限
					if (this.form.contractType !== '2' && this.form.entrustCycleDay == null) {
						this.$modal.msgError("非托管服务需要填写办理期限！");
						return;
					}
					// 续费合同需要选择首次签约日期
					if (this.form.isDue == 1 && this.form.firstSignDate == null) {
						this.$modal.msgError("续费合同需要选择首次签约日期！");
						return;
					}
					// 续费合同需要选择续费日期
					if (this.form.isDue == 1 && this.form.renewalDate == null) {
						this.$modal.msgError("续费合同需要选择续费日期！");
						return;
					}
					let isYearPayFlag = false;
					// 地址托管 需要选则年付或一次性
					this.form.checkedNodes.forEach(item => {
						if (!item.children && item.id == 25 && item.isYearPay == 0) {
							this.$modal.msgError("地址托管业务需要选则“年付”或“一次性付”！");
							isYearPayFlag = true
						}
					})
					if (isYearPayFlag) {
						return;
					}
					this.loading = true;
					// 如果非第一次生成合同，需要将原合同id传入form并提交
					if (!this.rowObj.firstGeneration) {
						//客户id
						this.form.customId = this.rowObj.customId;
						// renew 表示新生成续费合同，不需要传入原合同id
						if (!this.rowObj.renew) {
							//合同id
							this.form.id = this.rowObj.id;
						}
					} else {
						//客户id
						this.form.customId = this.rowObj.id;
					}
					if (!this.rowObj.isNew) {
						if (
							this.rowObj.renewCount === "" ||
							this.rowObj.renewCount == null ||
							this.rowObj.renewCount == undefined
						) {
							this.form.renewCount = 0;
						} else {
							this.form.renewCount = this.rowObj.renewCount + 1;
						}

						if (
							this.rowObj.parentIds === "" ||
							this.rowObj.parentIds === null ||
							this.rowObj.parentIds === undefined
						) {
							console.log("找不到parent");
							this.form.parentIds = this.rowObj.id + ";";
						} else {
							this.form.parentIds =
								this.form.parentIds + this.form.contractId + ";";
						}
					}
					if (this.form.contractType == "2") {
						this.form.renewStatus = 1;
					} else {
						this.form.renewStatus = 0;
					}
					// 如果是新签合同，需要将合同的签约日期赋值给首次签约日期
					if (this.form.isDue == 0) {
						this.form.firstSignDate = this.form.signDate;
					}
					// 老账新接
					this.form.oldAccounts = this.form.oldAccounts == true ? 1 : 0;
					// 构造接口参数数据
					this.form.contractBusinessList = [];
					// this.form.checkedNodes.forEach(item => {
					// 	if (!item.children) {
					// 		this.form.contractBusinessList.push({
					// 			businessId: item.id,
					// 			amount: item.amount,
					// 			note: item.noteOrMemo || item.note,
					// 			groupId: item.groupId,
					// 			otherNote: item.otherNote ? item.otherNote : null,
					// 			isYearPay: item.isYearPay
					// 		})
					// 	}
					// })
					if (this.form.contractType != 2) {
						this.form.isDue = 0;
					}
					// 将服务项目，存入提交的表单
					this.pushServiceItems();
					// 如果状态为预览，则调用预览接口，否则调用生成接口
					if (previewFlag) {
						this.pdfDialog.show = true;
						// 先将form表单提交到后台，后台临时生成pdf文件返回到前端，前端再展示
						preViewDetail(this.form)
							.then((res) => {
								this.loading = false;
								this.fileName = res.data.fileName;
								openPDF(res.data.fileName)
									.then((response) => {
										let blob = response;
										let blobURL = window.URL.createObjectURL(blob);
										this.blobURL = blobURL;
										this.pdfh5 = new Pdfh5("#previewPDF", {
											pdfurl: blobURL,
										});
									})
									.catch((err) => {
										this.loading = false;
									});
							})
							.catch((err) => {
								this.loading = false;
							});
					} else {
						// 新增生成合同
						addDetail(this.form).then((response) => {
							this.loading = false;
							this.closeDialog();
							this.$modal.msgSuccess('操作成功！');
						}).catch((err) => {
							this.loading = false;
						});
					}
				} else {
					this.$modal.msgError("验证未通过");
					return false;
				}
			});
		},
		// 服务项目存入表单
		pushServiceItems() {
			let that = this;
			let desFlag = false;//子孙是否有输入金额的标识
			let childIdstr = '';
			let otherNodeStr = '';
			let checkedNum = 0;
			let findDescendants = function (array) {
				array.forEach(item => {
					if (item.children) {
						findDescendants(item.children)
					} else {
						if (item.checked && (item.amount !== '' || item.noteOrMemo !== '')) {
							desFlag = true;
							that.form.contractBusinessList.push({
								businessId: item.id,
								amount: item.amount,
								child: '',
								note: item.noteOrMemo || item.note,
								groupId: item.groupId,
								otherNote: item.otherNote ? item.otherNote : null,
								isYearPay: item.isYearPay
							})
						} else if (item.checked && (item.amount == '' && item.noteOrMemo == '')) {
							// chuld 内值为 id+服务项目名称
							let nameStr = '';
							// 凡遇到lable名称包含“其他”字样的使用otherNode字段代替
							if (item.label.indexOf('其他') > -1) {
								nameStr = item.otherNote;
							} else {
								nameStr = item.label;
							}
							childIdstr += ',' + item.id + ':' + nameStr;
						}
						if (item.checked) {
							checkedNum += 1;
						}
					}
				})
				return {
					desFlag: desFlag,
					childIdstr: childIdstr,
					checkedNum: checkedNum
				};
			}

			let treeData = this.treeData[0].children;
			console.log('查找已选服务项目');
			treeData.forEach(item => {
				// 先判断父类节点是否有输入金额或备注：
				// ① 如果有，检查子孙类是否有输入金额：
				//      如果子孙类有输入金额，则仅计算子孙类金额
				// 			如果子孙类没有输入金额，则计算父类节点金额
				// ② 如果没有，则查找子孙类已选中并输入金额的节点
				checkedNum = 0;
				childIdstr = '';
				desFlag = false;
				if (item.amount !== '' || item.noteOrMemo !== '') {//父类节点有值，检查子孙类是否有值
					let obj = findDescendants(item.children);
					if (!obj.desFlag && obj.checkedNum > 0) {// 子孙类没有输入金额且已选中，则存入父类节点
						this.form.contractBusinessList.push({
							businessId: item.id,
							amount: item.amount,
							child: obj.childIdstr.substring(1),
							note: item.noteOrMemo || item.note,
							groupId: item.groupId,
							otherNote: item.otherNote ? item.otherNote : null,
							isYearPay: item.isYearPay
						})
					}
				} else {
					// 父类节点没有金额，只考虑子孙类节点
					findDescendants(item.children);
				}
			})
		},
		// 表单重置
		reset() {
			// 清空所有金额与备注
			function traverse(children) {
				children.forEach(child => {
					if (child.children) {
						child.checked = false;
						child.disabled = false;
						child.amount = '';
						child.noteOrMemo = '';
						if (child.otherNote) {
							child.otherNote = ''
						}
						traverse(child.children);
					} else {
						child.checked = false;
						child.disabled = false;
						child.amount = '';
						child.noteOrMemo = '';
						if (child.otherNote) {
							child.otherNote = ''
						}
					}
				});
			}
			this.form = {
				isDue: null,
				oldAccounts: false,
				firstSignDate: null,
				renewalDate: null,
				checkedNodes: [],
				groupDate: [],
				contractAmount: 0,
				entrustCycleDay: null,
				contractType: null,
				contractRemark: null,
				groupDateFlag: true,
				entrustCycleDayFlag: true,
				renewStatus: 0,
				partyB: "",
				payMode: '',
				partyName: "",
				partyCallName: "",
				partyCallPhone: "",
				// 签约日期
				signDate: null,
			};
			this.treeData.forEach(item => {
				this.$refs['treeDatas' + item.id][0].setCheckedKeys([]);
				this.$refs['treeDatas' + item.id][0].store._getAllNodes().forEach(item => {
					item.expanded = false;
				})
				traverse(item.children)
			})
			this.$refs.contractForm.clearValidate();
			this.$refs.contractForm.resetFields();
			this.form.oldAccounts = this.rowObj.oldAccounts == 1 ? true : 0,
				this.form.payMode = this.rowObj.payMode;
			this.form.entrustCycleDay = this.rowObj.entrustCycleDay;
			this.form.signDate = this.rowObj.signDate;
			this.form.partyName = this.rowObj.customName;
			this.form.partyCallName = this.rowObj.callName;
			this.form.partyCallPhone = this.rowObj.callPhone;
			this.form.contractRemark = this.rowObj.contractRemark;
			if (this.rowObj.entrustCycleStrat !== null && this.rowObj.entrustCycleStrat !== '') {
				this.form.groupDate[0] = this.rowObj.entrustCycleStrat;
				this.form.groupDate[1] = this.rowObj.entrustCycleEnd;
			}
			this.treeDefaultCheck = [];
			this.treeDefaultExpanded = [];
			if (!this.rowObj.firstGeneration) {
				this.getcontractItem();
			}
			this.changeContractType(this.rowObj.contractType);
		},
		// 获取服务项目
		getcontractItem() {
			let that = this;
			//获取上次合同的服务项目，并回填
			contractItem(this.rowObj.id).then((res) => {
				let checkArray = [];
				let contractArray = res.data;
				for (let i = 0; i < contractArray.length; i++) {
					if (!this.parentIds.includes(contractArray[i].businessId)) {// 父级id不设置选中
						checkArray.push(contractArray[i].businessId);
					}
					if (contractArray[i].child !== '' && contractArray[i].child !== null) { //如果是父级id，则会有child
						// 回填子级id
						let childArray = contractArray[i].child.split(',');
						for (let j = 0; j < childArray.length; j++) {
							checkArray.push(childArray[j].split(':')[0]);
						}
					}
					contractArray[i].id = contractArray[i].businessId;
					this.setValue(this.treeData[0].children, contractArray[i])
					// this.form.checkedNodes.push(contractArray[i])
				}
				this.$nextTick(() => {
					that.treeDefaultCheck = checkArray;
					that.treeDefaultExpanded = checkArray;
					that.form.contractType = that.rowObj.contractType + '';
					that.form.partyB = that.rowObj.partyB;
					// 生成续费合同时，是否续签默认选中续费
					if (that.rowObj.renew) {
						that.form.isDue = 1;
					} else {
						that.form.isDue = that.rowObj.isDue;
					}
					if (that.rowObj.isDue == 1) {
						that.form.firstSignDate = that.rowObj.firstSignDate;
						that.form.renewalDate = that.rowObj.renewalDate;
					}
				})
			})
		},
		// 回填金额
		setValue(childrens, obj) {
			let that = this;
			childrens.forEach(item => {
				if (item.children) {
					if (item.id == obj.businessId) {
						item.amount = obj.amount;
						item.noteOrMemo = obj.note == null ? '' : obj.note;
						item.isYearPay = obj.isYearPay;
						//item.checked = true;
						//this.form.checkedNodes.push(item)
						//this.eitherOr(item, true);
						if (obj.otherNote !== null && obj.otherNote !== '') {
							item.otherNote = obj.otherNote;
						}
						if (obj.child == null) {
							obj.child = ''
						}
						if (obj.child !== '') { //有子级，需要查找子级id对应的节点，checked设为true
							let childArr = obj.child.split(',');
							childArr.forEach(item => {
								let findchild = function (array) {
									array.some(child => {
										if (child.id == item.split(':')[0]) {
											child.checked = true;
											if (child.label.indexOf('其他') > -1) {//item的第二项赋值otherNode
												child.otherNote = item.split(':')[1]
											}
											that.form.checkedNodes.push(child)
											return true;
										}
										if (child.children) {
											findchild(child.children);
										}
									})
								}
								let array = this.treeData[0].children.find(child => child.id == obj.businessId).children;
								findchild(array);
							})
						}
					}
					this.setValue(item.children, obj)
				} else {
					if (item.id == obj.businessId) {
						item.amount = obj.amount;
						item.noteOrMemo = obj.note == null ? '' : obj.note;
						item.isYearPay = obj.isYearPay;
						item.checked = true;
						this.form.checkedNodes.push(item)
						this.eitherOr(item, true);
						if (obj.otherNote !== null && obj.otherNote !== '') {
							item.otherNote = obj.otherNote;
						}
					}
				}
			})
		},
		/*关闭弹框*/
		closeDialog() {
			this.$emit("closeDialog");
		},
		getPartyBOptions() {
			getPartyBOptions().then((response) => {
				this.partyBOptions = response.rows;
			});
		},
	},
};
</script>
<style scoped>
.contractForm {
	height: 75vh;
	overflow: auto;
}

.width18 {
	width: 180px;
	margin-top: 6px;
}

.notesClass {
	width: 180px;
	margin-left: 10px;
	margin-top: 6px;
}

.newTree /deep/ .el-tree-node__content {
	height: 40px !important;
}

.item-content /deep/ .pdfjs {
	height: 800px !important;
}

/* .el-input--medium /deep/ .el-input__inner {
	height: 28px;
	font-size: 13px;
	line-height: 28px;
} */
.el-radio .is-checked {
	margin-right: 10px;
}

@keyframes scroll {
	0% {
		transform: translateY(0);
	}

	100% {
		transform: translateY(-100%);
		/* 根据内容高度调整 */
	}
}
</style>